﻿package keyfun.loaders
{
	import flash.events.IEventDispatcher;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.display.Sprite;
	import keyfun.events.XMLLoaderEvent;
	import flash.events.ProgressEvent;
	 
	public class XMLLoader extends Sprite
	{
		private var _loader:URLLoader = new URLLoader();
		private var _xmlData:XML;
		private var _xmlFile:String;
		private var bytesLoaded:Number;
		private var bytesTotal:Number;
		public var isError:Boolean = false;
		private var _onCompleteFunc:Function;
		
		public function XMLLoader(xmlFile:String, onCompleteFunc:Function=null) 
		{
			_xmlFile = xmlFile;
			_onCompleteFunc = onCompleteFunc;
			addEvents(_loader);
			startLoad();
		}
		
		private function startLoad():void
		{
			_loader.load(new URLRequest(_xmlFile));
		}
		
		private function addEvents(dispatcher:IEventDispatcher):void
		{
			dispatcher.addEventListener(ProgressEvent.PROGRESS, progressHandler);
			dispatcher.addEventListener(Event.COMPLETE, completeHandler);
			dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
		}
		
		private function removeEvents(dispatcher:IEventDispatcher):void
		{
			dispatcher.removeEventListener(ProgressEvent.PROGRESS, progressHandler);
			dispatcher.removeEventListener(Event.COMPLETE, completeHandler);
			dispatcher.removeEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
		}
		
		private function ioErrorHandler(e:IOErrorEvent):void
		{
			removeEvents(_loader);
			isError = true;
			dispatchEvent(new XMLLoaderEvent(XMLLoaderEvent.ON_ERROR));
		}
		
		private function completeHandler(e:Event):void
		{
			removeEvents(_loader);
			
			_xmlData = new XML(e.target.data);
			parseXML(_xmlData);
		}
		
		private function progressHandler(e:ProgressEvent):void
		{
			if (_onCompleteFunc != null)
			{
				bytesLoaded = e.bytesLoaded;
				bytesTotal = e.bytesTotal;
				dispatchEvent(new XMLLoaderEvent(XMLLoaderEvent.ON_LOADING, { bytesLoaded:bytesLoaded, bytesTotal:bytesTotal } ));
			}
		}
		
		protected function parseXML(inputXML:XML):void
		{
			if (_onCompleteFunc != null)
			{
				_onCompleteFunc(inputXML);
			}
			else
			{
				dispatchEvent(new XMLLoaderEvent(XMLLoaderEvent.ON_COMPLETE, { xml:inputXML } ));
			}
		}
		
		////////////////////////////////////
		// Public function
		////////////////////////////////////
		
		public function getXML():XML
		{
			return _xmlData;
		}
		
	}
}